<?php
class BDA_Analytics {
    public static function init() {
        if (!wp_next_scheduled('bda_daily_analysis')) {
            wp_schedule_event(time(), 'daily', 'bda_daily_analysis');
        }
        add_action('bda_daily_analysis', [__CLASS__, 'run_daily_analysis']);
    }
    
    public static function run_daily_analysis() {
        global $wpdb;
        
        // User profile analysis
        $user_profiles = $wpdb->get_results(
            "SELECT user_id, 
                    COUNT(DISTINCT order_id) as order_count,
                    AVG(total_price) as avg_order_value,
                    SUM(total_price) as total_spent,
                    GROUP_CONCAT(DISTINCT category_id) as categories
             FROM {$wpdb->prefix}analytics_purchases
             GROUP BY user_id"
        );
        
        foreach ($user_profiles as $profile) {
            $categories = !empty($profile->categories) ? explode(',', $profile->categories) : [];
            $top_category = !empty($categories) ? array_count_values($categories) : [];
            arsort($top_category);
            $top_category = !empty($top_category) ? array_key_first($top_category) : 0;
            
            update_user_meta($profile->user_id, 'bda_user_profile', [
                'purchase_frequency' => $profile->order_count,
                'avg_order_value' => $profile->avg_order_value,
                'total_spent' => $profile->total_spent,
                'top_category' => $top_category,
                'last_updated' => current_time('mysql')
            ]);
        }
    }
    
    public static function get_user_segments($start_date, $end_date) {
        global $wpdb;
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT 
                u.user_id,
                u.order_count,
                u.avg_order_value,
                u.total_spent,
                u.top_category,
                a.ip_address,
                COUNT(DISTINCT a.id) as activity_count,
                MAX(a.created_at) as last_activity
             FROM (
                 SELECT 
                     user_id,
                     COUNT(DISTINCT order_id) as order_count,
                     AVG(total_price) as avg_order_value,
                     SUM(total_price) as total_spent,
                     GROUP_CONCAT(DISTINCT category_id) as categories,
                     SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT category_id ORDER BY category_id), ',', 1) as top_category
                 FROM {$wpdb->prefix}analytics_purchases
                 WHERE purchase_date BETWEEN %s AND %s
                 GROUP BY user_id
             ) u
             LEFT JOIN {$wpdb->prefix}analytics_user_actions a ON u.user_id = a.user_id
             GROUP BY u.user_id",
            $start_date, $end_date
        ));
    }
}